<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Login extends CI_Controller {

	function Login()
	{
		parent::__construct();
		// $this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->load->model('user','',TRUE);
		$this->form_validation->set_error_delimiters('<div class="help-inline">', '</div>');
	}

	public function index()
	{
		$data = array();

		if ( $this->input->post('login') == 'login' )
		{

			$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
			 
			if ( ! $this->form_validation->run() )
			{
				$data['error'] = 'Invalid username or password';
			}
			else
			{
				redirect(base_url('admin'), 'refresh');
			}
		}
		$data['loginValidationUrl'] = base_url('/login');
		$this->smarty->view('login.tpl',$data);
	}

	public function check_database($password)
	{
		//Field validation succeeded.  Validate against database
		$username = $this->input->post('username');
		//query the database
		$result = $this->user->login($username, $password);

		if($result)
		{
			$sess_array = array();
			foreach($result as $row)
			{
				$sess_array = array(
						'userid' => $row->user_id,
						'username' => $row->user_name
				);
				$this->session->set_userdata('logged_in', $sess_array);
			}
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function logout()
	{
		$this->session->unset_userdata('logged_in');
		session_destroy();
		redirect(base_url('login'), 'refresh');
	}

}

?>